﻿using System;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

using LeanEngine.Data.Linq.Language;

namespace LeanEngine.Data.Linq.Translator
{
    internal sealed class TakeTranslator : LinqTranslator<TakeToken>
    {
        #region Constructor Members

        private TakeToken _take;

        #endregion

        #region PropertyInfo Members

        public bool UseDefault { get; private set;}

        #endregion

        #region LinqTranslator<TakeToken> Members

        internal override bool CanEvaluate(QueryContext context)
        {
            switch(context.CurrentMethodCall.Method.Name)
            {
                case "First":
                    UseDefault = false;
                    return true;

                case "FirstOrDefault":
                    UseDefault = true;
                    return true;

                default:
                    return false;
            }
        }

        internal override TakeToken Interpret(QueryContext context)
        {
            _take = new TakeToken() { UseDefault = UseDefault };

            this.Evaluate(context.CurrentMethodCall);

            if (_take.Quantity == 0) _take.Quantity = 1;

            return _take;
        }

        #endregion

        #region Overrided Method Members

        protected override Expression EvaluateConstant(ConstantExpression c)
        {
            if (c.Type == typeof(Int32))
            {
                _take.Quantity = (Int32)c.Value;
            }

            return c;
        }

        #endregion
    }
}
